package com.bdqn.wang.dao.impl;

import java.sql.*;


public class BaseDao {
    //静态代码  初始化驱动
    static{
        try {
            //驱动
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("驱动连接");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() {
        try {
            //连接数据库
//			return DriverManager.getConnection("jdbc:mysql://localhost:3306/s2?useUnicode=true&characterEncoding=utf8", "root", "admin");
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/easybuy?useUnicode=true&characterEncoding=utf8", "root", "admin");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //关闭连接
    public static void closeAll(ResultSet rs,Statement stmt,Connection conn) {

        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
    //登录
    public PreparedStatement executeQurey(String sql, Object[] objs) {
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            //绑定参数
            if(objs!=null) {
                for (int i = 0; i < objs.length; i++) {
                    pstmt.setObject(i+1, objs[i]);
                }
            }
            return pstmt;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }
    //封装 增 删 改
    public int executeUpdate(String sql, Object[] objs) {
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            //绑定参数
            if(objs!=null) {
                for (int i = 0; i < objs.length; i++) {
                    pstmt.setObject(i+1, objs[i]);
                }
            }
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(null, pstmt, conn);
        }
        return 0;

    }

}


